package com.mryan.ps_auth.configure;

import com.mryan.ps_auth.properties.PSAuthProperties;
import com.mryan.ps_common.configure.PSAuthExceptionConfigure;
import com.mryan.ps_common.handle.PSAccessDeniedHandler;
import com.mryan.ps_common.handle.PSAuthExceptionEntryPoint;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @BelongsProject: ps_cloud
 * @BelongsPackage: com.mryan.ps_auth.configure
 * @Author: Yan
 * @CreateTime: 2021-04-23 21:00
 * @Description:
 */
@Configuration
@EnableResourceServer
public class PSResourceServerConfigure extends ResourceServerConfigurerAdapter {

	@Autowired
	private PSAuthExceptionEntryPoint psAuthExceptionEntryPoint;
	@Autowired
	private PSAccessDeniedHandler psAccessDeniedHandler;
	@Autowired
	private PSAuthProperties properties;

	@Override
	public void configure(HttpSecurity http) throws Exception {
		String[] anonURL = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(),",");

		http.csrf().disable()
				.requestMatchers().antMatchers("/**")
				.and()
				.authorizeRequests()
				.antMatchers(anonURL)
				.permitAll().antMatchers("/**")
				.authenticated()
				.and().httpBasic();
	}

	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		resources.authenticationEntryPoint(psAuthExceptionEntryPoint)
				.accessDeniedHandler(psAccessDeniedHandler);
	}
}
